<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\CallUser;
use plugin\admin\app\model\Like;
use plugin\admin\app\model\Exchange;
use plugin\admin\app\model\UserFollowing;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\Video;
use plugin\admin\app\model\VideoComment;
use plugin\admin\app\model\User;

class CommentService
{
    public static function beList($page, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $videos = Video::select(['id', 'thumb', 'desc'])->where('user_id', get_user_id())->get()->toArray();
        $videoIds = array_column($videos, 'id');
        $videos = array_combine(
            array_column($videos, 'id'),
            array_values($videos)
        );

        $query = VideoComment::select(['id', 'content', 'video_id', 'user_id', 'created_time'])->whereIn('video_id', $videoIds)->orWhere('reply_user_id', get_user_id());

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('id')->get()->toArray();

        $commentUserIds = array_column($list, 'user_id');
        $commentUsers =  UserProfile::select(['user_id', 'nickname', 'avatar', 'no'])->whereIn('user_id', $commentUserIds)->get()->toArray();
        $commentUsers = array_combine(
            array_column($commentUsers, 'user_id'),
            array_values($commentUsers)
        );

        foreach ($list as $key=>$item) {
            $item['user_info'] = $commentUsers[$item['user_id']];

            $video = $videos[$item['video_id']];
            $video['thumb'] = full_url($video['thumb']);
            $item['video_info'] = $video;

            $item['format_time'] = diff_time($item['created_time']);
            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function add($id, $content, $replayCommentId = 0, $callUserIds = [])
    {
        $replyUserId = 0;
        if ($replayCommentId > 0) {
            $comment = VideoComment::where('id', $replayCommentId)->first();
            $replyUserId = $comment['user_id'];
        }

        $commentId = VideoComment::insertGetId([
            'video_id' => $id,
            'user_id' => get_user_id(),
            'content' => $content,
            'reply_comment_id' => $replayCommentId,
            'top_comment_id' => self::getTopCommentId($replayCommentId),
            'reply_user_id' => $replyUserId,
            'created_time' => date('Y-m-d H:i:s')
        ]);

        CallUserService::add($commentId, $callUserIds);

        Video::where('id', $id)->increment('comments', 1);

        $comment = VideoComment::select(['id', 'user_id', 'reply_user_id', 'reply_comment_id', 'content', 'created_time', 'like_count', 'top_comment_id'])->where('id', $commentId)->first();

        $comment['is_like'] = false;
        $comment['is_reply_comment'] = 0;
        $comment['reply_comment_user_info'] = [];
        if ($comment['top_comment_id'] != $comment['reply_comment_id']) {
            $comment['is_reply_comment'] = 1;
            $comment['reply_comment_user_info'] = UserProfile::select(['user_id', 'nickname', 'avatar'])->where('user_id', $comment['reply_user_id'])->first();
        }

        $comment['time_text'] = diff_time($comment['created_time']);
        $comment['user_info'] = UserProfile::select(['user_id', 'nickname', 'avatar'])->where('user_id', $comment['user_id'])->first();

        return $comment;
    }

    public static function getTopCommentId($replyCommentId)
    {
        if ($replyCommentId == 0) {
            return 0;
        }

        $comment = VideoComment::where('id', $replyCommentId)->first();

        return $comment['reply_comment_id'] == 0 ? $comment['id'] : $comment['top_comment_id'];
    }

    public static function list($id, $page, $length = 10, $commentId = 0)
    {
        $offset = ($page - 1) * $length;
        $query = VideoComment::select(['id', 'user_id', 'reply_user_id', 'reply_comment_id', 'content', 'created_time', 'like_count', 'top_comment_id'])->where('video_id', $id)->where('reply_comment_id', $commentId);

        $totalCount = (clone $query)->count();
        $list = $query->orderByDesc('like_count')->offset($offset)->limit($length)->get()->toArray();

        $list = self::wrapList($list);

        if ($commentId == 0) {
            $eachSubCommentCount = 10;
            $subComments = VideoComment::select(['id', 'reply_comment_id', 'user_id', 'reply_user_id', 'content', 'created_time', 'like_count', 'top_comment_id'])->where('video_id', $id)->where('reply_comment_id', '>', 0)->orderByDesc('like_count')->offset(0)->limit(count($list) * $eachSubCommentCount)->get()->toArray();

            foreach ($list as $key=>$item) {
                $comments = [];

                foreach ($subComments as $subComment) {
                    if ($subComment['top_comment_id'] == $item['id']) {
                        $comments[] = $subComment;
                    }
                }
                $list[$key]['sub_comments'] = self::wrapList($comments);
            }
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    protected static function wrapList($list)
    {
        $userIds = array_column($list, 'user_id');
        $users = UserProfile::select(['user_id', 'nickname', 'avatar'])->whereIn('user_id', $userIds)->get()->toArray();
        $users = array_combine(
            array_column($users, 'user_id'),
            array_values($users)
        );

        $commentIds = array_column($list, 'id');
        $userLikeComments = Like::whereIn('third_party_id', $commentIds)->where('user_id', get_user_id())->where('type', Like::TYPE_COMMENT)->get()->toArray();
        $userLikeComments = array_combine(
            array_column($userLikeComments, 'third_party_id'),
            array_values($userLikeComments)
        );

        foreach ($list as $key=>$item) {
            $list[$key]['time_text'] = diff_time($item['created_time']);
            $list[$key]['user_info'] = $users[$item['user_id']];
            $list[$key]['is_like'] = isset($userLikeComments[$item['id']]);
            $list[$key]['is_reply_comment'] = 0;
            $list[$key]['reply_comment_user_info'] = [];

            if ($item['reply_user_id']) { //回复评论
                $list[$key]['is_reply_comment'] = 1;
                $list[$key]['reply_comment_user_info'] = $users[$item['reply_user_id']];
            }
        }

        return array_values($list);
    }

    public static function likeComment($commentId)
    {
        if (!self::isLikeComment($commentId)) {
            $comment = VideoComment::where('id', $commentId)->first();
            LikeService::like($commentId, $comment['user_id'], Like::TYPE_COMMENT, function ($commentId, $type) {
                VideoComment::where('id', $commentId)->increment('like_count', 1);
            });
        }
    }

    public static function isLikeComment($commentId)
    {
        return LikeService::isLike($commentId, Like::TYPE_COMMENT);
    }

    public static function cancelLikeComment($commentId)
    {
        LikeService::cancelLike($commentId, Like::TYPE_COMMENT, function ($commentId, $type) {
            VideoComment::where('id', $commentId)->decrement('like_count', 1);
        });
    }


}